/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc, Mathias De Maré
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package dijjer.io.comm;

import dijjer.util.AbstractThread;
import dijjer.util.logging.Logger;

public abstract class AbstractMulticastSocketManager extends AbstractThread {
	
	public static final String VERSION = "$Id: AbstractMulticastSocketManager.java 2 2008-03-21 14:33:03Z ian.clarke $";
	protected Dispatcher _dispatcher;
	protected boolean _isDone = false;
	protected static AbstractMulticastSocketManager _mcsm;
	protected final int _listenPort;
	
	public AbstractMulticastSocketManager(int listenPort) throws Exception {
		_listenPort = listenPort;
		startThread();
		getBaseThread().setName("MulticastSocketManager listener thread on port " + listenPort);
	}
	
	protected abstract boolean loop() throws InterruptedException;

	protected void cleanUp() {
		synchronized (this) {
			_isDone = true;
			notifyAll();
		}
	}
	
	public void shutdown(boolean exit) {
		synchronized (this) {
			while (!_isDone) {
				try {
					wait(2000);
				} catch (InterruptedException e) {
					Logger.error(e);
				}
			}
		}
	}

	public void setDispatcher(Dispatcher d) {
		_dispatcher = d;
	}
	
	public abstract String toString();
	
	public static AbstractMulticastSocketManager getMulticastSocketManager()
	{
		return _mcsm;
	}
	
	public static void init(AbstractMulticastSocketManager amsm) throws Exception {
		_mcsm = amsm;
	}
}
